import React, { useCallback, useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'
import { dataFetch } from '@pier88health/p8h-common'
import {
  WEB_NAV_HEIGHT,
  HIDE_NAV_PAGE,
  FIXED_PAGE,
  DECISION_PAGES,
  LANGUAGE,
  NAV_BG_COLOR_PAGE
} from '@CONSTANTS/app'
import { getPathname, isMobile } from '@UTILS/common'
import Images from '@ASSET/Images'
import { useAcPermission } from '@HOOKS/useSpringRainLogin'
import './index.scss'

export default function WebNav() {
  const onClickBack = useCallback(() => {
    window.history.back()
  }, [])
  const pathname = getPathname()
  const [currentRouter, setCurrentRouter] = useState(pathname)
  const changeRouter = useCallback(({ toLocation }) => {
    setCurrentRouter(toLocation.path)
  }, [setCurrentRouter])
  useEffect(() => {
    Taro.eventCenter.on('__taroRouterChange', changeRouter)
    return () => Taro.eventCenter.off('__taroRouterChange', changeRouter)
  }, [changeRouter])

  const url = window.location.href
  const { language } = dataFetch.getQueryParams(url)
  const isHide = HIDE_NAV_PAGE.includes(currentRouter)
  const { isSpringRain } = useAcPermission()
  console.log('isHide', isHide, currentRouter)
  const isHideTitle = language === LANGUAGE.EN && DECISION_PAGES.includes(currentRouter)
  if (isHide || isSpringRain) {
    return null
  }
  const isFixedNav = FIXED_PAGE.includes(currentRouter)
  const {
    isWhite,
    bgColor
  } = NAV_BG_COLOR_PAGE[currentRouter] || {}
  const style = { height: `${WEB_NAV_HEIGHT}px` }
  bgColor && (style.backgroundColor = bgColor)
  if (!isMobile()) {
    style.maxWidth = '375px'
    style.margin = 'auto'
  }
  return (
    <View
      id="webHeader"
      key={bgColor}
      className={`web-nav ${isFixedNav ? 'fixed' : ''} ${isWhite ? 'web-nav-white' : ''}`}
      style={style}
    >
      <Image src={isWhite ? Images.nav.back_white : Images.nav.back} className="web-nav-back" onClick={onClickBack} />
      <Text className="web-nav-page-title" id="pageTitle">{isHideTitle ? '' : document.title}</Text>
    </View>
  )
}
